import $http from '@/utils/x-request';

const state = {
  dictionary: {}
};

const mutations = {
  // 设置全局存储的字典map
  SET_DICTIONARY: (state, data) => {
    state.dictionary = {
      ...state.dictionary,
      ...data
    };
  }
};

const actions = {
  /*
   * 建议放在create函数中调用：
   * this.$store.dispatch('system/dictionary', 'BUSINESS_SEX, SYS_IDENTITY');
   * */
  dictionary({ commit, state }, names) {
    return new Promise(async(resolve, reject) => {
      names = typeof names === 'string' ? names.split(',').map(v => v.trim()) : names;
      // 初始化页面字典key
      const dictMap = Object.assign({}, state.dictionary);

      if (names[0]) {
        $http({
          url: '/account/dictionary/iu/list',
          method: 'get',
          data: { dictNames: names.join(',') }
        }).then((res) => {
          const data = res.data;
          for (let i = 0; i < data.length; i++) {
            dictMap[data[i].label] = data[i].children.map((val) => {
              return {
                ...val,
                val: /^(\-|\+)?\d+$/.test(val.value) ? +val.value : val.value
              };
            });
          }
          commit('SET_DICTIONARY', dictMap);
          resolve(dictMap);
        });
      } else {
        resolve(dictMap);
      }
    });
  }

};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
